package com.yz.test;

import java.security.SecureRandom;

public class RandomIDCardGenerator {
    public static void main(String[] args) {
        System.out.println(generateRandomIDCard());
    }

    public static String generateRandomIDCard() {
        SecureRandom random = new SecureRandom();
        StringBuilder idCard = new StringBuilder();

        // 生成前6位地区代码（这里简化为随机数字）
        for (int i = 0; i < 6; i++) {
            idCard.append(random.nextInt(10));
        }

        // 生成年份（1900-2099）
        int year = random.nextInt(100) + 1900;
        idCard.append(year);

        // 生成月份（01-12）
        int month = random.nextInt(12) + 1;
        if (month < 10) {
            idCard.append("0");
        }
        idCard.append(month);

        // 生成日期（01-31）
        int day = random.nextInt(31) + 1;
        if (day < 10) {
            idCard.append("0");
        }
        idCard.append(day);

        // 生成顺序码（000-999）
        for (int i = 0; i < 3; i++) {
            idCard.append(random.nextInt(10));
        }

        // 计算校验码并添加到末尾
        char checkCode = calculateCheckCode(idCard.toString());
        idCard.append(checkCode);

        return idCard.toString();
    }

    private static char calculateCheckCode(String idCardWithoutCheckCode) {
        int[] weights = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        char[] checkCodes = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
        int sum = 0;
        for (int i = 0; i < idCardWithoutCheckCode.length(); i++) {
            sum += (idCardWithoutCheckCode.charAt(i) - '0') * weights[i];
        }
        int remainder = sum % 11;
        return checkCodes[remainder];
    }
}

